package com.ali.sso.common.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * 跨域过滤器
 * @author cwang
 */
public class CrossDomainFilter extends AdviceFilter {
	private final static Logger log = LoggerFactory.getLogger(CrossDomainFilter.class);

	//同步session的url地址
	private String sessionIdSyncUrl; 
	//当前应用的域名
	private String domain; 

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = WebUtils.toHttp(request);
		HttpServletResponse  httpResponse = WebUtils.toHttp(response);
		Session session = SecurityUtils.getSubject().getSession(false);
		
		//session不为null, 则判断session的同步标识hasSyn
		if(session != null){
			//同步标识
			boolean hasSyn = (null == session.getAttribute("hasSyn") ? false : (Boolean)session.getAttribute("hasSyn"));
			
			//已同步（用户已登录 || 用户未登录但已同步session）
			if (SecurityUtils.getSubject().isAuthenticated() || hasSyn) {
				return true;
			}
			
			//未同步
			else
				return checkJsid(httpRequest, httpResponse);
		}
		
		//session为null，则重定向
		else
			return checkJsid(httpRequest, httpResponse);
		
	}
	
	private boolean checkJsid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String jsid = WebUtils.getCleanParam(request, "jsid");
		
		//jsid不为空
		if(StringUtils.isNotEmpty(jsid)){
			//以下两句作用是将jsid,rememberMe写到domain域名下的cookie中，读者可以自己实现。
			Cookie jsidCookie = new Cookie("sid", jsid);
			jsidCookie.setPath("/");
			jsidCookie.setDomain(domain);
			response.addCookie(jsidCookie);
			
//			SimpleCookie jsidSimple = new SimpleCookie();
//			jsidSimple.setPath("/");
//			jsidSimple.setName("jsid");
//			jsidSimple.setValue(jsid);
//			jsidSimple.setDomain(domain);
//			jsidSimple.saveTo(request, response);
			
			Cookie remMeCookie = new Cookie("rememberMe", WebUtils.getCleanParam(request, "rememberMe"));
			remMeCookie.setPath("/");
			remMeCookie.setDomain(domain);
			response.addCookie(remMeCookie);
			
//			String rememberMe = WebUtils.getCleanParam(request, "rememberMe");
//			byte[] decryptionKey = Base64.decode("4AvVhmFLUs0KTA3Kprsdag==");
			
			
//			SimpleCookie remMeSimple = new SimpleCookie();
//			remMeSimple.setPath("/");
//			remMeSimple.setName("rememberMe");
//			remMeSimple.setValue(WebUtils.getCleanParam(request, "rememberMe"));
//			remMeSimple.setDomain(domain);
//			remMeSimple.saveTo(request, response);
			
			WebUtils.issueRedirect(request, response, request.getRequestURL().toString());
			return false;
		}
		
		//jsid为空，则重定向
		else{
			String uri = sessionIdSyncUrl + "?service=" + request.getRequestURL().toString(); 
			WebUtils.issueRedirect(request, response, uri);
			log.info("redirect : " + uri);
			return false;
		}
	}
	
	public void setSessionIdSyncUrl(String sessionIdSyncUrl) {
		this.sessionIdSyncUrl = sessionIdSyncUrl;
	}
	public void setDomain(String domain) {
		this.domain = domain;
	}

}
